#ifndef CERTMANAGER_H
#define CERTMANAGER_H

#include <QObject>
#include <QAbstractTableModel>
#include <QMultiMap>
#include <QString>
#include <QHash>


#include "openssl/x509.h"

#include "certmgr/certtablemodel.h"


class CertManager : public QObject,
    public CertTableModel::Delegate
{
  Q_OBJECT
public:
  explicit CertManager(QObject *parent = nullptr);
  ~CertManager() override;

  void Init(bool with_nss = false);
  void UnInit();
  bool FindCert(const QString& keyword);
  bool VerifyCert(const QString& path, QString& errorMessage);
  bool ExportCert(const QString& path, int type, QString& errorMessage);

  void TraverseCert();


  // TODO
  void SetOption();
  void ReportError(int error_code, const QString& format, ...);

  void ReadCert(X509* cert);

  void ReadCertFile(const char* filePath);

  // override CertTableModel::Delegate
  QList<X509* > GetCertificates(const QString& category) override;
  QStringList GetCategories() override;
  const QVector<QString>& GetKeyUsageName() override {
    return key_usage_name_;
  }
  QStringList GetExtendedKeyUsage(X509* cert) override;

signals:
  void CertImported(const QString& category, int index);

private:
  void InitKeyUsageMap();

private:
  X509_STORE_CTX* x509_store_ctx_ = nullptr;
  X509_STORE*     x509_store_ = nullptr;
  STACK_OF(X509_OBJECT)* certs_ = nullptr;

  QMultiMap<QString, X509*> key_usage_map_;
  QMultiMap<QString, X509*> position_map_;
  QVector<QString> key_usage_name_;
};


#endif // CERTMANAGER_H
